<?php
/**
 * Conversations - A lightweight BB for Xaraya
 *
 * @package modules
 * @copyright (C) 2003-2006 The Digital Development Foundation.
 * @license GPL {@link http://www.gnu.org/licenses/gpl.html}
 * @link http://www.xaraya.com
 *
 * @subpackage conversations
 * @link http://xaraya.com/index.php/release/760.html
 * @author John Cox
*/
/**
 * Update a topic
*/

/**
 * merge a tag
 * @author John Cox
 * @author Jo dalle Nogare
 * @param $args['id'] integer
 * @param $args['tag'] string
 * @returns bool
 * @return true on success, NULL on failure
 */

function conversations_userapi_merge_tag($args)
{
    // Get arguments from argument array
    extract($args);
    
    if (!isset($id)){
        $id = $tagid;
    }

    if (!isset($id)) $invalid[] = "id";
    if (!isset($tag)) $invalid[] = "tag";
    
    // Argument check - make sure that paramter is present
    // if not then set an appropriate error message and return
    if (isset($invalid)) {
        $msg = xarML('Invalid parameter count');
        xarErrorSet(XAR_SYSTEM_EXCEPTION, 'BAD_PARAM', new SystemException($msg));
        return;
    }
    
    // Updating a tag name is a little different than just updating a post.
    // It is possible that we are merging the tag....
    // So we need to check and add it to our look up table, along with every post associated
    

    // First, let's see if the tag exists...
    // If this returns anything, then we know it does.
    $taginfo = xarModAPIFunc('conversations', 'user', 'gettags', array(
                                          'tag'   => $tag));
                                          
    // If it doesn't then get the hell out of here...                                      
    if (empty($taginfo)){
        return false;
    }
    
    // What is our new tag?
    $newtagid = $taginfo[0]['id'];
    
    // We need to get the posts associated with this tagid and move them to the new tagid
    $posts = xarModAPIFunc('conversations', 'user', 'getlook', array(
                                          'tagid'   => $id));
                                          

    // Make the move                             
    $totalposts = count($posts);
    for ($i = 0; $i < $totalposts; $i++) {
        $post = $posts[$i];
        xarModAPIFunc('conversations', 'user', 'updatelook', array(
                                        'tagid'     => $id,
                                        'postid'    => $posts[$i]['postid'],
                                        'newtagid'  => $newtagid));                
    }
 
    return true;
}
?>